//
//  SQLManager.swift
//  FMDB 演练
//
//  Created by 任玉林 on 16/7/8.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

private let dbName = "test.db"

class SQLManager{

    //单例
    static let sharedTools: SQLManager = SQLManager()
    
    //队列方式
    let queue: FMDatabaseQueue
    
    //构造函数
    private init(){
    
    //打开数据库
    let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
    
        queue = FMDatabaseQueue(path: path)
        
        //创建表
        createTable()
        
    }
    
    //创建表
    private func createTable(){
        
        //获取文件
        let file = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)
        
        //准备sql
        let sql = try! String(contentsOfFile: file!)
        
        //执行sql 
        queue.inDatabase { (db) -> Void in
            
            let result = db.executeStatements(sql)
            
            if result {
                
                print("表创建成功")
            }else{
                
                print("表创建失败")
            }
        }
        
    }
    
    //查询本地数据库中的数据，返回一个字典类型的数组
    func exeCoder(sql: String)-> [[String: AnyObject]]{
        
        var tempArray: [[String: AnyObject]] = [[String: AnyObject]]()
        SQLManager.sharedTools.queue.inDatabase { (db) -> Void in
            
            let reusltSet = db.executeQuery(sql, withArgumentsInArray: nil)
            
            //遍历
            while reusltSet.next(){
                
                var dict: [String: AnyObject] = [String: AnyObject]()
                
                for i in 0..<reusltSet.columnCount(){
                    
                    let name = reusltSet.columnNameForIndex(i)
                    
                    let value = reusltSet.objectForColumnIndex(i)
                    
                    dict[name] = value
                }
                
                tempArray.append(dict)
            }
        }
        
        return tempArray
        
    }
    
    
}
